package SolveQuestions;

import java.util.*;

public class l102 {
    class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
    }
    class Solution {
        public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> result = new ArrayList<>();
            Queue<TreeNode> record = new LinkedList<>();
            if(root == null) return result;
            record.add(root);

            while(!record.isEmpty()){
                int n = record.size();
                ArrayList<Integer> arr = new ArrayList<>();
                for(int i = 0; i < n; i ++) {
                    TreeNode temp = record.poll();
                    arr.add(temp.val);
                    if(temp.left != null) {
                        record.add(temp.left);
                    }
                    if(temp.right != null) {
                        record.add(temp.right);
                    }

                }
                result.add(arr);
            }
            return result;
        }
    }
}
